package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.dto.UserDTO;
import com.itheima.domain.entity.Follow;
import com.itheima.domain.entity.User;
import com.itheima.domain.vo.Result;
import com.itheima.mapper.FollowMapper;
import com.itheima.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.service.IUserService;
import com.itheima.utils.ThreadUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2025-10-06
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 查询用户是否关注
     */
    @Override
    public Result queryIsFollowed(Long followedUserId) {
        //获取登录用户id
        Long userId = ThreadUtil.get().getUserId();
        Boolean member = stringRedisTemplate.opsForSet().isMember("follow:user:" + userId, followedUserId.toString());
        return Result.ok(Boolean.TRUE.equals(member));
    }
    /**
     * 用户关注功能
     */
    @Override
    public Result follow(Long followedUserId, Boolean isFollow) {
        //获取当前登录用户id
        Long userId = ThreadUtil.get().getUserId();
        if(userId == null){//用户未登录,不允许关注
            return Result.fail("用户未登录,不允许关注");
        }
        if(isFollow){//关注
            //把followedUserId存入set集合中--sadd key value
            Long success = stringRedisTemplate.opsForSet().add("follow:user:" + userId, followedUserId.toString());
            if(success == 0){
                return Result.fail("关注失败");
            }
            //把关注信息存入数据库
            Follow follow = Follow.builder().userId(userId).followUserId(followedUserId).build();
            save(follow);
        }else {//取消关注
            //把followedUserId从set集合中移除--srem key value
            Long success = stringRedisTemplate.opsForSet().remove("follow:user:" + userId, followedUserId.toString());
            if(success == 0){
                return Result.fail("取消关注失败");
            }
            //把关注信息移出数据库
            LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Follow::getUserId,userId).eq(Follow::getFollowUserId,followedUserId);
            remove(queryWrapper);
        }
        return Result.ok();
    }
    /**
     * 查询共同关注
     */
    @Override
    public Result queryCommonFollowed(Long blogUserId) {
        //查询登录用户的信息
        Long userId = ThreadUtil.get().getUserId();
        String prefix = "follow:user:";
        Set<String> userIds = stringRedisTemplate.opsForSet().intersect(prefix + blogUserId, prefix + userId);
        if(CollectionUtil.isEmpty(userIds)){
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIdList = userIds.stream().map(Long::valueOf).toList();
        String strIds = StrUtil.join(",", userIdList);
        List<User> users = userService.lambdaQuery().in(User::getId, userIdList).last("order by field(id," + strIds + ")").list();
        List<UserDTO> userDTOS = users.stream().map(user -> {
            return BeanUtil.copyProperties(user, UserDTO.class);
        }).toList();
        return Result.ok(userDTOS);
    }
}
